<template>
  <view class="medicine-detail">
    <!-- 药品基本信息 -->
    <view class="basic-info">
      <image 
        :src="medicine.imageUrl" 
        mode="aspectFill" 
        class="medicine-image"
        @error="handleImageError"
      ></image>
      <view class="info-content">
        <text class="medicine-name">{{ medicine.medicineName }}</text>
        <view class="medicine-spec">
          <text>规格：{{ medicine.specification }}</text>
          <text>剂型：{{ medicine.dosageForm }}</text>
        </view>
        <view class="medicine-price-box">
          <text class="price">{{ formattedPrice }}</text>
          <text class="stock" :class="{ 'out-of-stock': isOutOfStock }">
            库存：{{ medicine.minStock > 0 ? medicine.minStock : 10 }}
          </text>
        </view>
      </view>
    </view>

    <!-- 药品分类信息 -->
    <view class="medicine-categories" v-if="medicine.commonCategoryName || medicine.prescriptionCategoryName">
      <text v-if="medicine.commonCategoryName" class="category-tag">
        {{ medicine.commonCategoryName }}
      </text>
      <text v-if="medicine.prescriptionCategoryName" class="category-tag rx">
        {{ medicine.prescriptionCategoryName }}
      </text>
    </view>

    <!-- 药品详情选项卡 -->
    <view class="detail-tabs">
      <view 
        class="tab-item" 
        v-for="(tab, index) in tabs" 
        :key="index" 
        :class="{ active: currentTab === index }"
        @click="switchTab(index)"
      >
        {{ tab }}
      </view>
    </view>

    <!-- 详情内容 -->
    <swiper class="detail-swiper" :current="currentTab" @change="handleSwiperChange">
      <!-- 药品说明 -->
      <swiper-item>
        <scroll-view scroll-y class="detail-scroll">
          <view class="detail-section">
            <view class="section-item">
              <text class="section-title">药品成分</text>
              <text class="section-content">{{ medicine.ingredients || '暂无信息' }}</text>
            </view>
            <view class="section-item">
              <text class="section-title">适应症</text>
              <text class="section-content">{{ medicine.indications || '暂无信息' }}</text>
            </view>
            <view class="section-item">
              <text class="section-title">禁忌症</text>
              <text class="section-content">{{ medicine.contraindications || '暂无信息' }}</text>
            </view>
            <view class="section-item">
              <text class="section-title">生产厂家</text>
              <text class="section-content">{{ medicine.manufacturer || '暂无信息' }}</text>
            </view>
            <view class="section-item">
              <text class="section-title">批准文号</text>
              <text class="section-content">{{ medicine.approvalNumber || '暂无信息' }}</text>
            </view>
            <view class="section-item">
              <text class="section-title">保质期</text>
              <text class="section-content">{{ medicine.shelfLife ? medicine.shelfLife + '个月' : '暂无信息' }}</text>
            </view>
            <view class="section-item">
              <text class="section-title">储存条件</text>
              <text class="section-content">{{ medicine.storageCondition || '暂无信息' }}</text>
            </view>
          </view>
        </scroll-view>
      </swiper-item>

      <!-- 用药指导 -->
      <swiper-item>
        <scroll-view scroll-y class="detail-scroll">
          <view class="detail-section">
            <view class="section-item">
              <text class="section-title">用法用量</text>
              <text class="section-content">{{ medicine.usage || '请遵医嘱' }}</text>
            </view>
            <view class="section-item">
              <text class="section-title">注意事项</text>
              <text class="section-content">{{ medicine.precautions || '请遵医嘱' }}</text>
            </view>
            <view class="section-item">
              <text class="section-title">不良反应</text>
              <text class="section-content">{{ medicine.sideEffects || '暂无信息' }}</text>
            </view>
            <view class="section-item">
              <text class="section-title">药物相互作用</text>
              <text class="section-content">{{ medicine.interactions || '暂无信息' }}</text>
            </view>
          </view>
        </scroll-view>
      </swiper-item>

      <!-- 用户评价 -->
      <swiper-item>
        <scroll-view 
          scroll-y 
          class="detail-scroll"
          @scrolltolower="loadMoreEvaluations"
        >
          <view class="evaluation-section">
            <!-- 评分概览 -->
            <view class="evaluation-header">
              <view class="evaluation-summary">
                <text class="score">{{ averageScore }}</text>
                <text class="score-text">综合评分</text>
              </view>
              <!-- 移除登录检查，所有用户都可以评价 -->
              <button 
                class="add-evaluation-btn" 
                @click="showEvaluationForm"
              >
                写评价
              </button>
            </view>
            
            <!-- 评价列表 -->
            <view class="evaluation-list">
              <view 
                v-for="item in evaluations" 
                :key="item.evaluationId" 
                class="evaluation-item"
              >
                <view class="evaluation-header">
                  <view class="user-info">
                    <image 
                      :src="item.userAvatar || '/static/images/default-avatar.png'" 
                      class="user-avatar"
                    ></image>
                    <view class="user-detail">
                      <text class="user-name">{{ item.userName }}</text>
                      <view class="score-stars">
                        <text 
                          v-for="i in 5" 
                          :key="i" 
                          class="star" 
                          :class="{ active: i <= item.evaluationScore }"
                        >★</text>
                      </view>
                    </view>
                  </view>
                  <text class="evaluation-time">{{ formatTime(item.createTime) }}</text>
                </view>
                <text class="evaluation-content">{{ item.evaluationContent }}</text>
                
                <!-- 评价操作栏 -->
                <view class="evaluation-actions">
                  <view class="action-item" @click="toggleLike(item)">
                    <text class="icon" :class="{ active: item.isLiked }">👍</text>
                    <text class="count">{{ item.likeCount || 0 }}</text>
                  </view>
                  <view class="action-item" @click="showReplyInput(item)">
                    <text class="icon">💬</text>
                    <text class="count">{{ item.replyCount || 0 }}</text>
                  </view>
                </view>

                <!-- 回复列表 -->
                <view class="reply-list" v-if="item.replies && item.replies.length">
                  <view 
                    v-for="reply in item.replies" 
                    :key="reply.replyId" 
                    class="reply-item"
                  >
                    <text class="reply-user">{{ reply.userName || '管理员' }}</text>
                    <text class="reply-content">{{ reply.replyContent }}</text>
                    <text class="reply-time">{{ formatTime(reply.createTime) }}</text>
                  </view>
                </view>
                
                <!-- 回复输入框 -->
                <view class="reply-input-container" v-if="item.showReplyInput">
                  <input 
                    type="text" 
                    v-model="item.replyContent" 
                    class="reply-input"
                    placeholder="写下你的回复..." 
                    focus
                    @blur="hideReplyInput(item)"
                  />
                  <button 
                    class="reply-submit" 
                    @tap.stop="submitReply(item)"
                  >回复</button>
                </view>
              </view>
            </view>
            
            <!-- 加载状态 -->
            <view class="loading-state" v-if="loadingEvaluations">
              <text>加载中...</text>
            </view>
            
            <!-- 空状态 -->
            <view class="empty-state" v-if="!evaluations.length && !loadingEvaluations">
              <text>暂无评价</text>
            </view>
            
            <!-- 加载完成 -->
            <view class="load-all" v-if="!hasMoreEvaluations && evaluations.length">
              <text>没有更多评价了</text>
            </view>
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>

    <!-- 底部操作栏优化 -->
    <view class="action-bar">
      <view class="action-icons">
        <view class="icon-item" @tap.stop="handleCartClick">
          <view class="icon cart-icon">
            <text v-if="cartCount > 0" class="cart-badge">{{ cartCount }}</text>
        </view>
          <text class="icon-text">购物车</text>
        </view>
        <view class="icon-item favorite-icon" @tap="toggleFavorite">
          <text class="icon">{{ isFavorite ? '❤️' : '♡' }}</text>
          <text class="text">收藏</text>
        </view>
      </view>
      <view class="buy-buttons">
        <button 
          class="add-to-cart-btn" 
          @tap.stop="handleAddToCartClick"
          :disabled="isOutOfStock"
        >
          加入购物车
        </button>
        <button 
          class="buy-now-btn" 
          @tap.stop="handleBuyNowClick"
          :disabled="isOutOfStock"
        >
          立即购买
        </button>
      </view>
    </view>

    <!-- 数量选择弹窗 -->
    <uni-popup ref="quantityPopup" type="bottom">
      <view class="quantity-popup">
        <view class="popup-header">
          <text class="title">{{ medicine.medicineName }}</text>
          <text class="close" @click="closeQuantityPopup">×</text>
        </view>
        <view class="popup-content">
          <!-- 商品信息 -->
          <view class="medicine-brief">
            <image 
              :src="medicine.imageUrl" 
              class="brief-image"
              @error="handleImageError"
            ></image>
            <view class="brief-info">
              <text class="brief-price">¥{{ medicine.price }}</text>
              <text class="brief-stock">库存：{{ medicine.minStock > 0 ? medicine.minStock : 10 }}</text>
            </view>
          </view>

          <!-- 数量选择器 -->
          <view class="quantity-selector">
            <text class="label">购买数量</text>
            <view class="selector">
              <view 
                class="minus" 
                :class="{ disabled: quantity <= 1 }" 
                @click="handleMinusClick"
              >-</view>
              <input 
                type="number"
                class="quantity-input"
                :value="quantity" 
                @input="handleQuantityInput"
                @blur="handleQuantityBlur"
              />
              <view 
                class="plus" 
                :class="{ disabled: quantity >= medicine.minStock }" 
                @click="handlePlusClick"
              >+</view>
            </view>
          </view>

          <!-- 总价展示 -->
          <view class="total-price">
            <text class="label">总价：</text>
            <text class="price">¥{{ totalPrice }}</text>
          </view>
        </view>

        <view class="popup-footer">
          <button 
            class="confirm-btn" 
            hover-class="button-hover"
            @tap="handleConfirm"
          >
            确定
          </button>
        </view>
      </view>
    </uni-popup>

    <!-- 评价表单弹窗优化 -->
    <uni-popup ref="evaluationPopup" type="bottom">
      <view class="evaluation-form">
        <view class="form-header">
          <text class="title">写评价</text>
          <text class="close" @click="closeEvaluationForm">×</text>
        </view>
        <view class="form-content">
          <view class="rating-box">
            <view class="rating-item">
              <text class="rating-label">综合评分</text>
              <view class="stars">
                <text 
                  v-for="i in 5" 
                  :key="i" 
                  class="star"
                  :class="{ active: i <= newEvaluation.evaluationScore }"
                  @click="setScore('evaluation', i)"
                >★</text>
              </view>
            </view>
          </view>
          <view class="content-box">
            <text class="label">评价内容</text>
            <textarea
              class="evaluation-textarea"
              v-model="newEvaluation.evaluationContent"
              placeholder="分享你的使用感受，对他人很有帮助哦~"
              maxlength="500"
            ></textarea>
            <text class="word-count">{{ newEvaluation.evaluationContent ? newEvaluation.evaluationContent.length : 0 }}/500</text>
          </view>
          <view class="anon-box">
            <text class="label">匿名评价</text>
            <switch 
              :checked="newEvaluation.isAnonymous"
              @change="(e) => newEvaluation.isAnonymous = e.detail.value"
            />
          </view>
        </view>
        <view class="form-footer">
          <button 
            class="submit-btn" 
            :disabled="!isEvaluationValid"
            @click="submitEvaluation"
          >
            发表评价
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { medicineApi } from '@/api/medicine'
import { cartApi } from '@/api/cart'
import checkLogin from '@/mixins/checkLogin'

export default {
  data() {
    return {
      medicineId: '',
      medicine: {
        medicineId: '',
        medicineName: '',
        imageUrl: '',
        specification: '',
        dosageForm: '',
        price: 0,
        minStock: 10
      },
      tabs: ['药品说明', '用药指导', '用户评价'],
      currentTab: 0,
      evaluations: [],
      evaluationPage: 1,
      evaluationPageSize: 10,
      hasMoreEvaluations: true,
      loadingEvaluations: false,
      averageScore: 0,
      cartCount: 0,
      isFavorite: false,
      quantity: 1,
      buyType: '',
      newEvaluation: {
        evaluationScore: 5,
        evaluationContent: '',
        isAnonymous: false
      },
      evaluationRules: {
        content: [
          { required: true, message: '请输入评价内容' },
          { min: 5, message: '评价内容至少5个字' }
        ]
      },
      reportTypes: [
        { label: '虚假信息', value: 'fake' },
        { label: '广告营销', value: 'ad' },
        { label: '违法违规', value: 'illegal' },
        { label: '人身攻击', value: 'attack' },
        { label: '其他问题', value: 'other' }
      ],
      reportForm: {
        type: '',
        content: '',
        evaluationId: null
      },
      maxStock: 10, // 最大库存数量
    }
  },

  computed: {
    formattedPrice() {
      return this.medicine.price ? `¥${this.medicine.price.toFixed(2)}` : '暂无价格'
    },
    
    isOutOfStock() {
      return this.medicine.minStock <= 0;
    },

    canSubmit() {
      return this.newEvaluation.evaluationContent.trim().length >= 5 && 
             this.newEvaluation.evaluationScore > 0 && 
             this.newEvaluation.orderId
    },

    maxStock() {
      return this.medicine.minStock > 0 ? this.medicine.minStock : 10;
    },

    isEvaluationValid() {
      return this.newEvaluation && 
             this.newEvaluation.evaluationContent && 
             this.newEvaluation.evaluationContent.length >= 5 && 
             this.newEvaluation.evaluationScore > 0;
    },

    totalPrice() {
      const price = Number(this.medicine.price) || 0;
      const quantity = Number(this.quantity) || 0;
      return (price * quantity).toFixed(2);
    }
  },

  onLoad(options) {
    try {
      console.log('详情页加载参数:', options);
    if (options.id) {
        this.medicineId = options.id;
        this.loadMedicineDetail();
        this.loadEvaluations(true);
        this.getCartCount();
        this.checkFavorite();
      } else {
        throw new Error('缺少药品ID参数');
      }
    } catch (error) {
      console.error('页面加载错误:', error);
      uni.showToast({
        title: '页面加载失败',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } finally {
      // 添加弹窗组件检测
      this.$nextTick(() => {
        if (!this.$refs.quantityPopup) {
          console.error('警告: quantityPopup 组件未找到!');
          // 可以在这里添加修复逻辑或提示用户
        }
      });
    }
  },

  onError(error) {
    console.error('全局错误:', error);
    uni.showToast({
      title: '操作异常，请重试',
      icon: 'none'
    });
  },

  onShow() {
    // 检查弹窗状态
    this.checkPopupStatus();
  },

  methods: {
    ...checkLogin,

    async loadMedicineDetail() {
      try {
        uni.showLoading({ title: '加载中...' })
        
        const detailRes = await medicineApi.getMedicineDetail(this.medicineId)
        console.log('药品详情响应:', detailRes)
        
        if (detailRes.code === 200 && detailRes.data) {
          // 直接获取药品数据
          let medicineData = detailRes.data;
          
          // 如果数据嵌套在data字段中，则取出该字段
          if (detailRes.data.data) {
            medicineData = detailRes.data.data;
          }
          
          if (medicineData) {
            // 确保正确处理库存数量
            let stockQuantity = 0;
            
            // 尝试获取库存信息
            try {
            const stockRes = await medicineApi.getMedicineStock(this.medicineId)
            console.log('库存信息响应:', stockRes)
              
              if (stockRes.code === 200 && stockRes.data) {
                stockQuantity = Number(stockRes.data.stockQuantity) || 0;
              }
            } catch (stockError) {
              console.error('获取库存信息失败:', stockError);
              // 如果获取库存失败，尝试使用药品信息中的库存
              stockQuantity = Number(medicineData.minStock || medicineData.stockQuantity || 0);
            }
            
            // 如果minStock不存在或为0，但有其他库存字段，则使用其他字段
            if (stockQuantity <= 0) {
              stockQuantity = Number(medicineData.stockQuantity || medicineData.stock || 10); // 默认值10用于测试
            }
            
            this.medicine = {
              ...this.medicine,
              ...medicineData,
              medicineId: medicineData.medicineId,
              medicineName: medicineData.medicineName,
              imageUrl: medicineData.imageUrl,
              specification: medicineData.specification,
              dosageForm: medicineData.dosageForm,
              approvalNumber: medicineData.approvalNumber,
              manufacturer: medicineData.manufacturer,
              shelfLife: medicineData.shelfLife,
              storageCondition: medicineData.storageCondition,
              ingredients: medicineData.ingredients,
              indications: medicineData.indications,
              contraindications: medicineData.contraindications,
              commonCategoryId: medicineData.commonCategoryId,
              commonCategoryName: medicineData.commonCategoryName,
              prescriptionCategoryId: medicineData.prescriptionCategoryId,
              prescriptionCategoryName: medicineData.prescriptionCategoryName,
              usage: medicineData.usageMethod || '',
              precautions: medicineData.precautionNotes || '',
              sideEffects: medicineData.sideEffectDescriptions || '',
              interactions: medicineData.drugInteractionDetails || '',
              salesVolume: medicineData.salesVolume,
              // 确保 stockQuantity 和 minStock 使用相同的值
              stockQuantity: stockQuantity,
              minStock: stockQuantity,
              price: Number(medicineData.price) || 0
            }
            
            console.log('处理后的药品数据:', this.medicine)
            this.maxStock = this.medicine.stock || 0; // 设置最大库存
          } else {
            throw new Error('药品数据格式错误')
          }
        } else {
          throw new Error(detailRes.errorMessage || '获取药品详情失败')
        }
      } catch (error) {
        console.error('加载药品详情失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none',
          duration: 2000
        })
        
        // 为了测试，可以设置默认值
        this.medicine.minStock = 10;
        this.medicine.price = 36.00;
        
        setTimeout(() => {
          uni.navigateBack()
        }, 2000)
      } finally {
        uni.hideLoading()
      }
    },

    async loadEvaluations(reset = false) {
      if (this.loadingEvaluations && !reset) return;
      
      try {
        this.loadingEvaluations = true;
        console.log('开始加载评价列表');
        
        if (reset) {
          this.evaluationPage = 1;
          this.evaluations = [];
        }

        // 检查medicineId
        if (!this.medicineId) {
          throw new Error('药品ID不能为空');
        }

        console.log('当前页码:', this.evaluationPage);
        console.log('每页数量:', this.evaluationPageSize);

        const res = await medicineApi.getMedicineEvaluations({
          medicineId: this.medicineId,
          pageNum: this.evaluationPage,
          pageSize: this.evaluationPageSize
        });

        console.log('评价列表API响应:', res);

        if (res.code === 200 && res.data) {
          const { records, total } = res.data;
          console.log('评价记录数:', records?.length);
          console.log('总记录数:', total);
          
          if (Array.isArray(records) && records.length > 0) {
            // 格式化评价数据
            const formattedEvaluations = records.map(item => ({
              evaluationId: item.evaluationId || item.id,
              userName: item.isAnonymous ? '匿名用户' : (item.userName || '用户'),
              userAvatar: item.userAvatar || '/static/images/default-avatar.png',
              evaluationScore: Number(item.evaluationScore) || 0,
              evaluationContent: item.evaluationContent || '',
              createTime: item.createTime || new Date().toISOString(),
              likeCount: Number(item.likeCount) || 0,
              isLiked: Boolean(item.isLiked),
              replyCount: Number(item.replyCount) || 0,
              replies: []
            }));
            
            console.log('格式化后的评价数据:', formattedEvaluations);
            
            // 更新评价列表
            this.evaluations = reset ? formattedEvaluations : [...this.evaluations, ...formattedEvaluations];
            
            // 更新是否有更多数据
            this.hasMoreEvaluations = this.evaluations.length < total;
            
            // 计算平均评分
            const totalScore = formattedEvaluations.reduce((sum, item) => sum + item.evaluationScore, 0);
            this.averageScore = formattedEvaluations.length > 0 
              ? (totalScore / formattedEvaluations.length).toFixed(1)
              : '0.0';
            
            console.log('当前评价列表:', this.evaluations);
            console.log('是否有更多数据:', this.hasMoreEvaluations);
            console.log('平均评分:', this.averageScore);
          } else {
            console.log('没有找到评价记录');
            if (reset) {
              this.evaluations = [];
              this.averageScore = '0.0';
            }
            this.hasMoreEvaluations = false;
          }
        } else {
          throw new Error(res.msg || '获取评价失败');
        }
      } catch (error) {
        console.error('加载评价失败:', error);
        uni.showToast({
          title: error.message || '加载评价失败',
          icon: 'none'
        });
      } finally {
        this.loadingEvaluations = false;
        uni.stopPullDownRefresh();
      }
    },
    
    // 加载所有评价的回复
    async loadAllReplies() {
      try {
        const promises = this.evaluations.map(evaluation => 
          this.loadReplies(evaluation.evaluationId)
        );
        await Promise.all(promises);
      } catch (error) {
        console.error('加载回复失败:', error);
      }
    },
    
    // 加载单个评价的回复
    async loadReplies(evaluationId) {
      try {
        const res = await medicineApi.getEvaluationReplies(evaluationId);
        
        if (res.code === 200 && res.data) {
          const replies = Array.isArray(res.data) ? res.data : [];
          
          // 更新评价的回复列表
          const evaluationIndex = this.evaluations.findIndex(item => 
            item.evaluationId === evaluationId
          );
          
          if (evaluationIndex > -1) {
            // 格式化回复数据
            const formattedReplies = replies.map(reply => ({
              replyId: reply.id || reply.replyId,
              userName: reply.isAnonymous ? '匿名用户' : (reply.userName || '用户'),
              replyContent: reply.replyContent || '',
              createTime: reply.createTime || new Date().toISOString()
            }));
            
            this.$set(this.evaluations[evaluationIndex], 'replies', formattedReplies);
            this.$set(this.evaluations[evaluationIndex], 'replyCount', formattedReplies.length);
          }
        }
      } catch (error) {
        console.error(`加载评价ID: ${evaluationId} 的回复失败:`, error);
      }
    },

    loadMoreEvaluations() {
      if (this.hasMoreEvaluations && !this.loadingEvaluations) {
        this.evaluationPage++;
        this.loadEvaluations();
      }
    },

    switchTab(index) {
      this.currentTab = index;
    },

    handleSwiperChange(e) {
      this.currentTab = e.detail.current;
    },

    async getCartCount() {
      try {
        const userId = this.getUserId();
        if (userId) {
          const res = await cartApi.getCartCount(userId);
          if (res.code === 200) {
            this.cartCount = res.data || 0;
          }
        } else {
          this.cartCount = 0;
        }
      } catch (error) {
        console.error('获取购物车数量失败:', error);
        this.cartCount = 0;
      }
    },

    checkFavorite() {
      const favorites = uni.getStorageSync('medicineFavorites') || [];
      this.isFavorite = favorites.some(item => item.medicineId === this.medicineId);
    },

    toggleFavorite() {
      const favorites = uni.getStorageSync('medicineFavorites') || [];
      
      if (this.isFavorite) {
        const newFavorites = favorites.filter(item => item.medicineId !== this.medicineId);
        uni.setStorageSync('medicineFavorites', newFavorites);
        this.isFavorite = false;
        uni.showToast({
          title: '已取消收藏',
          icon: 'none'
        });
      } else {
        favorites.push({
          medicineId: this.medicineId,
          medicineName: this.medicine.medicineName,
          imageUrl: this.medicine.imageUrl,
          price: this.medicine.price,
          specification: this.medicine.specification,
          dosageForm: this.medicine.dosageForm,
          addTime: new Date().getTime()
        });
        uni.setStorageSync('medicineFavorites', favorites);
        this.isFavorite = true;
        uni.showToast({
          title: '收藏成功',
          icon: 'success'
        });
      }
    },

    handleBuyAction(type) {
      console.log('触发购买操作:', type);
      
      // 检查库存
      const maxStock = this.medicine.minStock > 0 ? this.medicine.minStock : 10;
      if (maxStock <= 0) {
        uni.showToast({
          title: '商品已售罄',
          icon: 'none'
        });
        return;
      }
      
      // 检查用户登录状态
      let userId = null;
      try {
        const userInfo = uni.getStorageSync('userInfo');
        userId = userInfo ? (userInfo.userId || userInfo.id) : null;
      } catch (e) {
        console.error('获取用户信息失败:', e);
      }
      
      if (!userId) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/login/login' });
        }, 1500);
        return;
      }
      
      // 购买类型（购物车或立即购买）
      this.buyType = type;
      
      // 打开数量选择弹窗，默认数量为1
      this.quantity = 1;
      this.openQuantityPopup();
    },

    // 修改数量输入处理方法
    handleQuantityInput(event) {
      let value = parseInt(event.detail.value);
      const maxStock = this.medicine.minStock || 10;
      
      if (isNaN(value) || value < 1) {
        value = 1;
      } else if (value > maxStock) {
        value = maxStock;
        uni.showToast({
          title: `库存不足，当前库存${maxStock}`,
          icon: 'none'
        });
      }
      
      this.quantity = value;
      console.log('输入数量:', this.quantity);
    },

    // 验证数量
    validateQuantity() {
      const quantity = parseInt(this.quantity) || 0;
      
      if (quantity <= 0) {
        uni.showToast({
          title: '请选择购买数量',
          icon: 'none'
        });
        return false;
      }
      
      const maxStock = this.medicine.minStock || 10;
      if (quantity > maxStock) {
        uni.showToast({
          title: `库存不足，当前库存${maxStock}`,
          icon: 'none'
        });
        return false;
      }
      
      return true;
    },

    // 验证库存
    validateStock(quantity) {
      if (!this.medicine || !this.medicine.minStock) {
        uni.showToast({
          title: '库存信息不可用',
          icon: 'none'
        });
        return false;
      }
      
      if (quantity > this.medicine.minStock) {
        uni.showToast({
          title: `库存不足，当前库存${this.medicine.minStock}`,
          icon: 'none'
        });
        return false;
      }
      
      return true;
    },

    // 修改确认按钮处理方法
    async handleConfirm() {
      try {
        console.log('确认按钮被点击');
        
        // 验证数量
        if (!this.validateQuantity()) {
          return;
        }

        // 构建订单项数据
        const orderItem = {
          medicineId: this.medicine.medicineId,
          medicineName: this.medicine.medicineName,
          specification: this.medicine.specification,
          dosageForm: this.medicine.dosageForm,
          price: Number(this.medicine.price),
          quantity: parseInt(this.quantity),
          imageUrl: this.medicine.imageUrl,
          totalPrice: (Number(this.medicine.price) * parseInt(this.quantity)).toFixed(2)
        };

        console.log('订单项数据:', orderItem);

        // 保存订单数据到本地存储
        try {
          uni.removeStorageSync('checkoutItems');
          uni.setStorageSync('checkoutItems', [orderItem]);
          console.log('成功保存订单数据到本地存储');
        } catch (storageError) {
          console.error('保存订单数据失败:', storageError);
          throw new Error('保存订单数据失败');
        }

        // 关闭弹窗
        if (this.$refs.quantityPopup) {
          this.$refs.quantityPopup.close();
        }

        // 等待弹窗完全关闭
        await new Promise(resolve => setTimeout(resolve, 300));

        // 尝试跳转到订单确认页面
        console.log('准备跳转到订单确认页面');
        const url = '/pages/pharmacy/order-confirm';
        
        try {
          await uni.navigateTo({
            url,
            fail: async (error1) => {
              console.error('navigateTo失败:', error1);
              
              try {
                await uni.redirectTo({
                  url,
                  fail: async (error2) => {
                    console.error('redirectTo失败:', error2);
                    
                    await uni.reLaunch({
                      url,
                      fail: (error3) => {
                        console.error('reLaunch失败:', error3);
                        throw new Error('无法跳转到订单确认页面');
                      }
                    });
                  }
                });
              } catch (navError) {
                console.error('所有导航方法都失败:', navError);
                throw new Error('导航到订单确认页面失败');
              }
            }
          });
        } catch (error) {
          console.error('跳转失败:', error);
          uni.showModal({
            title: '跳转失败',
            content: '无法跳转到订单确认页面，请稍后重试',
            showCancel: false
          });
        }
      } catch (error) {
        console.error('确认操作失败:', error);
        uni.showToast({
          title: error.message || '操作失败，请重试',
          icon: 'none',
          duration: 2000
        });
      }
    },

    // 添加数量验证方法
    validateStock(quantity) {
      if (!this.medicine || typeof this.medicine.stock === 'undefined') {
        uni.showToast({
          title: '商品信息不完整',
          icon: 'none'
        });
        return false;
      }

      const requestedQuantity = parseInt(quantity);
      if (isNaN(requestedQuantity) || requestedQuantity < 1) {
        uni.showToast({
          title: '请输入有效的购买数量',
          icon: 'none'
        });
        return false;
      }

      if (requestedQuantity > this.medicine.stock) {
        uni.showToast({
          title: `库存不足，当前库存${this.medicine.stock}`,
          icon: 'none'
        });
        return false;
      }

      return true;
    },

    // 添加图片加载错误处理
    handleImageError() {
      this.medicine.imageUrl = '/static/images/medicine-default.png'
    },

    // 获取用户ID
    getUserId() {
      try {
        const token = uni.getStorageSync('token');
        if (token) {
          // 尝试解析token中的用户信息
          const tokenData = typeof token === 'string' ? JSON.parse(token) : token;
          return tokenData.id || null;
        }
        return null;
      } catch (error) {
        console.error('获取用户ID失败:', error);
        return null;
      }
    },

    // 提交评价
    async submitEvaluation() {
      try {
        // 参数校验
        if (!this.medicineId) {
          uni.showToast({
            title: '药品ID不能为空',
            icon: 'none'
          });
          return;
        }

        if (!this.newEvaluation.evaluationContent) {
          uni.showToast({
            title: '评价内容不能为空',
            icon: 'none'
          });
          return;
        }

        const content = this.newEvaluation.evaluationContent.trim();
        if (content.length < 5) {
          uni.showToast({
            title: '评价内容至少5个字',
            icon: 'none'
          });
          return;
        }

        if (!this.newEvaluation.evaluationScore || 
            this.newEvaluation.evaluationScore < 1 || 
            this.newEvaluation.evaluationScore > 5) {
          uni.showToast({
            title: '评分必须在1-5之间',
            icon: 'none'
          });
          return;
        }

        // 构建评价数据
        const evaluationData = {
          medicineId: parseInt(this.medicineId),
          evaluationScore: this.newEvaluation.evaluationScore,
          evaluationContent: content,
          isAnonymous: this.newEvaluation.isAnonymous || false
        };

        uni.showLoading({ title: '提交中...' });

        const res = await medicineApi.addMedicineEvaluation(evaluationData);

        if (res.code === 200) {
          // 构建新评价对象
          const newEvaluation = {
            evaluationId: res.data || Date.now(), // 如果后端没返回ID，使用时间戳
            userName: evaluationData.isAnonymous ? '匿名用户' : (uni.getStorageSync('userInfo')?.userName || '用户'),
            userAvatar: uni.getStorageSync('userInfo')?.avatarUrl || '/static/images/default-avatar.png',
            evaluationScore: evaluationData.evaluationScore,
            evaluationContent: evaluationData.evaluationContent,
            createTime: new Date().toISOString(),
            likeCount: 0,
            isLiked: false,
            replyCount: 0,
            replies: [],
            isAnonymous: evaluationData.isAnonymous
          };

          // 将新评价添加到列表开头
          this.evaluations.unshift(newEvaluation);

          // 更新评分
          this.updateAverageScore();

          uni.showToast({
            title: '评价发表成功',
            icon: 'success'
          });

          // 关闭评价弹窗
          if (this.$refs.evaluationPopup) {
            this.$refs.evaluationPopup.close();
          }

          // 重置评价表单
          this.newEvaluation = {
            evaluationScore: 5,
            evaluationContent: '',
            isAnonymous: false
          };

        } else {
          throw new Error(res.msg || '评价发表失败');
        }
      } catch (error) {
        console.error('提交评价失败:', error);
        uni.showToast({
          title: error.message || '评价发表失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 更新平均评分
    updateAverageScore() {
      if (!this.evaluations.length) {
        this.averageScore = '0.0';
        return;
      }
      
      const totalScore = this.evaluations.reduce((sum, item) => sum + item.evaluationScore, 0);
      this.averageScore = (totalScore / this.evaluations.length).toFixed(1);
    },

    // 显示评价表单
    showEvaluationForm() {
      // 重置评价表单
      this.newEvaluation = {
        evaluationScore: 5,
        evaluationContent: '',
        isAnonymous: false
      };

      // 打开评价弹窗
      if (this.$refs.evaluationPopup) {
        this.$refs.evaluationPopup.open('bottom');
      }
    },

    // 设置评分
    setScore(type, score) {
      if (type === 'evaluation') {
        this.newEvaluation.evaluationScore = score;
      }
    },

    closeEvaluationForm() {
      if (this.$refs.evaluationPopup) {
        this.$refs.evaluationPopup.close();
      }
    },

    // 点赞/取消点赞
    async toggleLike(evaluation) {
      try {
        const res = await medicineApi.toggleEvaluationLike(evaluation.evaluationId)
        
        if (res.code === 200) {
          // 更新本地评价数据的点赞状态
          const evaluationIndex = this.evaluations.findIndex(item => 
            item.evaluationId === evaluation.evaluationId
          )
          
          if (evaluationIndex > -1) {
            const currentLiked = this.evaluations[evaluationIndex].isLiked
            this.$set(this.evaluations[evaluationIndex], 'isLiked', !currentLiked)
            
            // 更新点赞数量
            const currentLikeCount = this.evaluations[evaluationIndex].likeCount || 0
            this.$set(
              this.evaluations[evaluationIndex], 
              'likeCount', 
              currentLiked ? Math.max(0, currentLikeCount - 1) : currentLikeCount + 1
            )
          }
          
          uni.showToast({
            title: evaluation.isLiked ? '已取消点赞' : '点赞成功',
            icon: 'none'
          })
        } else {
          throw new Error(res.msg || '操作失败')
        }
      } catch (error) {
        console.error('点赞操作失败:', error)
        uni.showToast({
          title: error.message || '操作失败',
          icon: 'none'
        })
      }
    },

    // 显示回复输入框
    showReplyInput(evaluation) {
      // 先隐藏所有其他评价的回复输入框
      this.evaluations.forEach(item => {
        if (item.evaluationId !== evaluation.evaluationId) {
          this.$set(item, 'showReplyInput', false);
          this.$set(item, 'replyContent', '');
        }
      });
      
      // 切换当前评价的回复输入框显示状态
      this.$set(evaluation, 'showReplyInput', !evaluation.showReplyInput);
      if (!evaluation.showReplyInput) {
        this.$set(evaluation, 'replyContent', '');
      }
    },
    
    // 隐藏回复输入框
    hideReplyInput(evaluation) {
      // 延迟执行，避免点击提交按钮时输入框就消失了
      setTimeout(() => {
        this.$set(evaluation, 'showReplyInput', false);
      }, 200);
    },
    
    // 提交回复
    async submitReply(evaluation) {
      // 验证回复内容
      if (!evaluation.replyContent || evaluation.replyContent.trim() === '') {
        uni.showToast({
          title: '请输入回复内容',
          icon: 'none'
        })
        return
      }
      
      try {
        const replyData = {
          evaluationId: evaluation.evaluationId,
          replyContent: evaluation.replyContent.trim(),
          // 如果用户未登录，使用默认值
          userId: uni.getStorageSync('userInfo')?.userId || 'anonymous'
        }
        
        uni.showLoading({ title: '提交中...' })
        
        const res = await medicineApi.addEvaluationReply(replyData)
        
        uni.hideLoading()
        
        if (res.code === 200) {
          uni.showToast({
            title: '回复成功',
            icon: 'success'
          })
          
          // 清空输入框并隐藏
          this.$set(evaluation, 'replyContent', '')
          this.$set(evaluation, 'showReplyInput', false)
          
          // 重新加载回复列表
          await this.loadReplies(evaluation.evaluationId)
        } else {
          throw new Error(res.msg || '回复失败')
        }
      } catch (error) {
        console.error('回复失败:', error)
        uni.showToast({
          title: error.message || '回复失败',
          icon: 'none'
        })
      }
    },

    // 选择订单
    selectOrder(orderId) {
      this.newEvaluation.orderId = orderId
    },

    // 上传图片
    async chooseImage() {
      try {
        if (this.newEvaluation.images.length >= 3) {
          uni.showToast({
            title: '最多只能上传3张图片',
            icon: 'none'
          });
          return;
        }
        
        const res = await uni.chooseImage({
          count: 3 - this.newEvaluation.images.length,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera']
        });
        
        // 处理选择的图片
        const tempFilePaths = res.tempFilePaths;
        for (let path of tempFilePaths) {
          // 直接使用本地图片路径，无需上传到服务器
          this.newEvaluation.images.push(path);
        }
      } catch (error) {
        console.error('选择图片失败:', error);
        uni.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    },

    // 删除已选图片
    removeImage(index) {
      this.newEvaluation.images.splice(index, 1);
    },

    formatTime(time) {
      if (!time) return '未知时间';
      
      try {
        const date = new Date(time);
        if (isNaN(date.getTime())) return time;
        
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      } catch (error) {
        console.error('时间格式化失败:', error);
        return time;
      }
    },

    previewImage(images, index) {
      if (!images || !images.length) return;
      
      try {
        uni.previewImage({
          urls: images,
          current: images[index]
        });
      } catch (error) {
        console.error('预览图片失败:', error);
        uni.showToast({
          title: '预览图片失败',
          icon: 'none'
        });
      }
    },

    // 修改弹窗打开与关闭方法，增加错误处理
    openQuantityPopup() {
      this.quantity = 1; // 重置数量为1
      this.$refs.quantityPopup.open();
    },

    closeQuantityPopup() {
      this.$refs.quantityPopup.close();
    },

    // 修复底部按钮点击事件
    /**
     * 处理购物车按钮点击
     */
    handleCartClick() {
      console.log('购物车按钮被点击');
      // 检查用户是否登录
      const userId = this.getUserId();
      if (!userId) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/login/login' });
        }, 1500);
        return;
      }
      
      // 跳转到购物车页面
      uni.navigateTo({
        url: '/pages/pharmacy/cart',
        success: () => {
          console.log('成功跳转到购物车页面');
        },
        fail: (err) => {
          console.error('跳转购物车页面失败:', err);
          uni.showToast({
            title: '跳转失败，请稍后再试',
            icon: 'none'
          });
        }
      });
    },

    /**
     * 处理加入购物车按钮点击
     */
    async handleAddToCartClick() {
      try {
        console.log('加入购物车按钮被点击');
        
        // 检查用户登录状态
        const userId = this.getUserId();
        if (!userId) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          });
          setTimeout(() => {
            uni.navigateTo({ url: '/pages/login/login' });
          }, 1500);
          return;
        }

        // 检查库存
        const maxStock = this.medicine.minStock > 0 ? this.medicine.minStock : 10;
        if (maxStock <= 0) {
          uni.showToast({
            title: '商品已售罄',
            icon: 'none'
          });
          return;
        }

        // 获取用户选择的数量
        const selectedQuantity = parseInt(this.quantity) || 1;
        
        // 验证数量
        if (selectedQuantity > maxStock) {
          uni.showToast({
            title: `库存不足，当前库存${maxStock}`,
            icon: 'none'
          });
          return;
        }

        // 添加到购物车，使用用户选择的数量
        const cartItemData = {
          medicineId: this.medicine.medicineId,
          medicineName: this.medicine.medicineName,
          specification: this.medicine.specification,
          dosageForm: this.medicine.dosageForm,
          price: Number(this.medicine.price),
          quantity: selectedQuantity,
          imageUrl: this.medicine.imageUrl
        };

        uni.showLoading({ title: '添加中...' });

        try {
          const res = await cartApi.addToCart(cartItemData, userId);
          
          uni.hideLoading();
          
          if (res.code === 200) {
            uni.showToast({
              title: '已加入购物车',
              icon: 'success'
            });
            
            // 更新购物车数量
            this.getCartCount();
            
            // 重置数量选择
            this.quantity = 1;
          } else {
            throw new Error(res.msg || '加入购物车失败');
          }
        } catch (error) {
          uni.hideLoading();
          console.error('加入购物车失败:', error);
          uni.showToast({
            title: error.message || '加入购物车失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('处理加入购物车操作失败:', error);
        uni.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        });
      }
    },

    /**
     * 处理立即购买按钮点击
     */
    async handleBuyNowClick() {
      try {
        console.log('立即购买按钮被点击');
        
        // 检查用户登录状态
        const userInfo = uni.getStorageSync('userInfo');
        if (!userInfo) {
          uni.showToast({
            title: '请先登录',
            icon: 'none',
            duration: 2000
          });
          
          // 延迟跳转到登录页
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/login/login'
            });
          }, 1000);
          return;
        }
        
        // 获取用户ID
        const userId = this.getUserIdentifier();
        if (!userId) {
          uni.showModal({
            title: '提示',
            content: '登录信息异常，请重新登录',
            success: (res) => {
              if (res.confirm) {
                uni.navigateTo({
                  url: '/pages/login/login'
                });
              }
            }
          });
          return;
        }

        // 检查商品库存
        if (this.isOutOfStock) {
          uni.showToast({
            title: '商品已售罄',
            icon: 'none'
          });
          return;
        }

        // 设置购买类型
        this.purchaseType = 'buy';
        
        // 打开数量选择弹窗
        if (this.$refs.quantityPopup) {
          this.$refs.quantityPopup.open();
        } else {
          // 如果弹窗组件不存在，直接处理购买逻辑
          this.handleConfirm(1); // 默认购买数量为1
        }
      } catch (error) {
        console.error('立即购买处理失败:', error);
        uni.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        });
      }
    },

    /**
     * 直接跳转到购物车页面
     */
    directToCart() {
      try {
        console.log('直接跳转到购物车');
        
        // 使用不同的跳转方式尝试
        uni.reLaunch({
          url: '/pages/pharmacy/cart',
          success: () => {
            console.log('成功跳转到购物车页面');
          },
          fail: (err) => {
            console.error('reLaunch跳转失败:', err);
            
            // 如果reLaunch失败，尝试navigateTo
            uni.navigateTo({
              url: '/pages/pharmacy/cart',
              fail: (navErr) => {
                console.error('navigateTo也失败了:', navErr);
                
                // 最后尝试switchTab
                uni.switchTab({
                  url: '/pages/pharmacy/cart',
                  fail: (switchErr) => {
                    console.error('所有跳转方式都失败:', switchErr);
                    uni.showModal({
                      title: '跳转失败',
                      content: '无法跳转到购物车页面，请手动返回首页',
                      showCancel: false
                    });
                  }
                });
              }
            });
          }
        });
      } catch (error) {
        console.error('跳转购物车页面异常:', error);
      }
    },

    /**
     * 测试按钮可点击性
     */
    testButtonClickability() {
      console.log('测试按钮可点击性');
      
      // 输出按钮状态信息
      const actionBar = document.querySelector('.action-bar');
      if (actionBar) {
        console.log('底部操作栏存在');
        
        // 检查购物车按钮
        const cartBtn = document.querySelector('.icon-item');
        if (cartBtn) {
          console.log('购物车按钮存在');
        } else {
          console.warn('购物车按钮不存在或无法获取');
        }
        
        // 检查加入购物车按钮
        const addToCartBtn = document.querySelector('.add-to-cart-btn');
        if (addToCartBtn) {
          console.log('加入购物车按钮存在');
        } else {
          console.warn('加入购物车按钮不存在或无法获取');
        }
      } else {
        console.warn('底部操作栏不存在或无法获取');
      }
    },

    /**
     * 直接添加到购物车（不使用弹窗）
     */
    async directAddToCart() {
      try {
        // 检查用户登录
        const userId = this.getUserId();
        if (!userId) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          });
          setTimeout(() => {
            uni.navigateTo({ url: '/pages/login/login' });
          }, 1500);
          return;
        }
        
        // 创建购物车项
        const cartItemData = {
          medicineId: this.medicine.medicineId,
          quantity: 1 // 默认添加1件
        };
        
        uni.showLoading({ title: '添加中...' });
        
        // 调用API添加到购物车
        const res = await cartApi.addToCart(cartItemData, userId);
        
        uni.hideLoading();
        
        if (res.code === 200) {
          uni.showToast({
            title: '已加入购物车',
            icon: 'success'
          });
          
          // 更新购物车数量
          this.getCartCount();
        } else {
          throw new Error(res.errorMessage || '加入购物车失败');
        }
      } catch (error) {
        console.error('直接添加购物车失败:', error);
        uni.showToast({
          title: '添加失败，请重试',
          icon: 'none'
        });
      }
    },

    /**
     * 检测并修复界面交互问题
     */
    checkAndFixInteraction() {
      // 检查底部按钮是否可点击
      setTimeout(() => {
        const addToCartBtn = document.querySelector('.add-to-cart-btn');
        const buyNowBtn = document.querySelector('.buy-now-btn');
        
        // 如果按钮存在但不可点击，添加备用点击处理
        if (addToCartBtn) {
          addToCartBtn.addEventListener('click', () => {
            console.log('备用点击处理: 加入购物车');
            this.directAddToCart();
          });
        }
        
        if (buyNowBtn) {
          buyNowBtn.addEventListener('click', () => {
            console.log('备用点击处理: 立即购买');
            this.emergencyBuyNow();
          });
        }
      }, 1000);
      
      // 添加全局点击事件处理
      document.addEventListener('click', (e) => {
        console.log('点击元素:', e.target);
      });
    },

    // 添加这些方法
    handleMinusClick() {
      if (this.quantity > 1) {
        this.quantity--;
        console.log('减少数量:', this.quantity);
      }
    },

    handlePlusClick() {
      const maxStock = this.medicine.minStock || 10;
      if (this.quantity < maxStock) {
        this.quantity++;
        console.log('增加数量:', this.quantity);
      } else {
        uni.showToast({
          title: `库存不足，当前库存${maxStock}`,
          icon: 'none'
        });
      }
    },

    handleQuantityBlur(event) {
      let value = parseInt(event.detail.value);
      const maxStock = this.medicine.minStock || 10;
      
      if (isNaN(value) || value < 1) {
        this.quantity = 1;
      } else if (value > maxStock) {
        this.quantity = maxStock;
        uni.showToast({
          title: `库存不足，当前库存${maxStock}`,
          icon: 'none'
        });
      }
      
      console.log('失焦后数量:', this.quantity);
    },

    // 初始化可用库存
    checkPopupStatus() {
      // 设置最大可购买数量为药品库存
      this.maxStock = this.medicine.minStock || 10;
      console.log('设置最大库存:', this.maxStock);
    },

    // 添加备用跳转方法
    async navigateToOrderConfirm() {
      const url = '/pages/pharmacy/order-confirm';
      
      try {
        // 方法1: 使用navigateTo
        await new Promise((resolve, reject) => {
          uni.navigateTo({
            url,
            success: resolve,
            fail: reject
          });
        });
        return;
      } catch (error1) {
        console.error('navigateTo失败:', error1);
        
        try {
          // 方法2: 使用redirectTo
          await new Promise((resolve, reject) => {
            uni.redirectTo({
              url,
              success: resolve,
              fail: reject
            });
          });
          return;
        } catch (error2) {
          console.error('redirectTo失败:', error2);
          
          try {
            // 方法3: 使用reLaunch
            await new Promise((resolve, reject) => {
              uni.reLaunch({
                url,
                success: resolve,
                fail: reject
              });
            });
            return;
          } catch (error3) {
            console.error('所有跳转方法都失败');
            throw new Error('无法跳转到订单确认页面');
          }
        }
      }
    },

    // 添加获取用户标识的方法
    getUserIdentifier() {
      try {
        const userInfo = uni.getStorageSync('userInfo');
        console.log('当前用户信息:', userInfo);
        
        if (!userInfo) {
          console.error('未找到用户信息');
          return null;
        }
        
        // 优先使用 id，如果没有则使用 pkId（注意大小写）
        const userId = userInfo.id || userInfo.pkId;
        console.log('获取到的用户标识:', userId);
        
        if (!userId) {
          console.error('用户信息中没有有效的标识');
          return null;
        }
        
        return userId;
      } catch (error) {
        console.error('获取用户标识失败:', error);
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return null;
      }
    },
  }
}
</script>

<style lang="scss">
.medicine-detail {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 120rpx;

  .basic-info {
    background: #fff;
    padding: 30rpx;
    display: flex;
    
    .medicine-image {
      width: 240rpx;
      height: 240rpx;
      border-radius: 12rpx;
      margin-right: 30rpx;
      background: #f5f5f5;
    }
    
    .info-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      
      .medicine-name {
        font-size: 32rpx;
        color: #333;
        font-weight: bold;
        margin-bottom: 20rpx;
      }
      
      .medicine-spec {
        margin-bottom: 20rpx;
        
        text {
          display: block;
          font-size: 26rpx;
          color: #666;
          margin-bottom: 10rpx;
        }
      }
      
      .medicine-price-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .price {
          font-size: 36rpx;
          color: #ff4d4f;
          font-weight: bold;
        }
        
        .stock {
          font-size: 26rpx;
          color: #999;
        }
      }
    }
  }

  .detail-tabs {
    display: flex;
    background: #fff;
    margin-top: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .tab-item {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      font-size: 28rpx;
      color: #666;
      position: relative;
      
      &.active {
        color: #007AFF;
        font-weight: bold;
        
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 60rpx;
          height: 4rpx;
          background: #007AFF;
          border-radius: 2rpx;
        }
      }
    }
  }

  .detail-swiper {
    height: calc(100vh - 500rpx);
    background: #fff;
    
    .detail-scroll {
      height: 100%;
    }
  }

  .detail-section {
    padding: 30rpx;
    
    .section-item {
      margin-bottom: 30rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .section-title {
        display: block;
        font-size: 28rpx;
        color: #333;
        font-weight: bold;
        margin-bottom: 16rpx;
      }
      
      .section-content {
        font-size: 26rpx;
        color: #666;
        line-height: 1.6;
      }
    }
  }

  .evaluation-section {
    padding: 30rpx;
    
    .evaluation-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;
      
      .evaluation-summary {
        text-align: center;
        margin-bottom: 30rpx;
        
        .score {
          font-size: 48rpx;
          color: #ff4d4f;
          font-weight: bold;
        }
        
        .score-text {
          font-size: 26rpx;
          color: #666;
          margin-left: 10rpx;
        }
      }
      
      .add-evaluation-btn {
        background: #ffb800;
        color: #fff;
        padding: 10rpx 20rpx;
        border-radius: 40rpx;
        font-size: 26rpx;
        height: 60rpx;
        line-height: 60rpx;
        border: none;
        box-shadow: 0 4rpx 8rpx rgba(255, 184, 0, 0.2);
      }
    }
    
    .evaluation-list {
      .evaluation-item {
        background: #fff;
        margin-bottom: 20rpx;
        padding: 30rpx !important;
        border-radius: 12rpx;
        
        .user-info {
          .user-avatar {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
            margin-right: 20rpx;
          }
          
          .user-detail {
            .user-name {
              font-size: 28rpx !important;
              font-weight: bold;
            }
          }
        }
        
        .evaluation-content {
          font-size: 28rpx !important;
          margin: 20rpx 0;
        }
        
        .evaluation-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 16rpx;
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .no-more,
      .empty-list {
        text-align: center;
        padding: 30rpx 0;
        
        text {
          font-size: 26rpx;
          color: #999;
        }
      }
    }

    .evaluation-images {
      display: flex;
      flex-wrap: wrap;
      margin-top: 16rpx;
      
      .evaluation-image {
        width: 160rpx;
        height: 160rpx;
        margin-right: 10rpx;
        margin-bottom: 10rpx;
        border-radius: 8rpx;
      }
    }
    
    .loading-state,
    .empty-state,
    .load-all {
      text-align: center;
      padding: 30rpx;
      color: #999;
      font-size: 26rpx;
    }
  }

  .action-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding: 0 20rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    z-index: 100;
    
    .action-icons {
      display: flex;
      
      .icon-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-right: 30rpx;
        position: relative;
        
        .icon {
          width: 44rpx;
          height: 44rpx;
          position: relative;
        }
        
        .cart-badge {
          position: absolute;
          top: -10rpx;
          right: -10rpx;
          background-color: #ff5500;
          color: #fff;
          font-size: 20rpx;
          height: 30rpx;
          min-width: 30rpx;
          line-height: 30rpx;
          text-align: center;
          border-radius: 15rpx;
          padding: 0 6rpx;
        }
        
        .icon-text {
          font-size: 20rpx;
          color: #666;
          margin-top: 6rpx;
        }
      }
    }
    
    .buy-buttons {
      flex: 1;
      display: flex;
      justify-content: flex-end;
      
      button {
        height: 70rpx;
        line-height: 70rpx;
        font-size: 28rpx;
        border-radius: 35rpx;
        margin: 0 0 0 20rpx;
        padding: 0 30rpx;
        opacity: 1;
        z-index: 101;
        position: relative;
        
        &[disabled] {
          opacity: 0.6;
        }
        
        &:active {
          opacity: 0.8;
        }
      }
      
      .add-to-cart-btn {
        background: linear-gradient(to right, #ffb800, #ff9500);
        color: #fff;
        min-width: 200rpx;
      }
      
      .buy-now-btn {
        background: linear-gradient(to right, #ff7300, #ff5500);
        color: #fff;
        min-width: 180rpx;
      }
    }
  }

  .quantity-popup {
    background-color: #fff;
    border-top-left-radius: 24rpx;
    border-top-right-radius: 24rpx;
    overflow: hidden;
    position: relative;
    z-index: 9999 !important;
    
    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 30rpx;
      position: relative;
      
      &::after {
        content: '';
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        height: 1px;
        background: #f2f2f2;
        transform: scaleY(0.5);
      }
      
      .title {
        font-size: 30rpx;
        color: #333;
        font-weight: 500;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .close {
        padding: 10rpx;
        font-size: 36rpx;
        color: #999;
        line-height: 1;
        margin: -10rpx;
      }
    }
    
    .popup-content {
      padding: 30rpx;
      
      .medicine-brief {
        display: flex;
        margin-bottom: 30rpx;
        
        .brief-image {
          width: 160rpx;
          height: 160rpx;
          border-radius: 8rpx;
          margin-right: 20rpx;
          background: #f5f5f5;
        }
        
        .brief-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          
          .brief-price {
            font-size: 36rpx;
            color: #ff5500;
            font-weight: bold;
            margin-bottom: 15rpx;
          }
          
          .brief-stock {
            font-size: 24rpx;
            color: #666;
          }
        }
      }
      
      .quantity-selector {
        margin-bottom: 30rpx;
        
        .label {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 20rpx;
          display: block;
          font-weight: 500;
        }
        
        .selector {
          display: flex;
          align-items: center;
          height: 70rpx;
          
          .minus, .plus {
            z-index: 10;
            position: relative;
            padding: 0;
            width: 80rpx;
            height: 80rpx;
            
            &:active {
              background-color: #e0e0e0;
            }
          }
          
          .quantity-input {
            z-index: 5;
            padding: 0 10rpx;
          }
        }
      }

      .total-price {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 30rpx;

        .label {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }

        .price {
          font-size: 36rpx;
          color: #ff5500;
          font-weight: bold;
        }
      }
    }
    
    .popup-footer {
      padding: 20rpx 30rpx 40rpx;
      
      .confirm-btn {
        height: 88rpx;
        line-height: 88rpx;
        background: linear-gradient(to right, #ff7500, #ff5500);
        color: #fff;
        font-size: 30rpx;
        font-weight: 500;
        border-radius: 44rpx;
        text-align: center;
        transition: all 0.2s;
        box-shadow: 0 8rpx 16rpx rgba(255, 85, 0, 0.2);
        z-index: 10000 !important;
        
        &:active {
          opacity: 0.9;
          transform: scale(0.98);
        }
      }
    }
  }
}

.evaluation-list {
  .evaluation-item {
    background: #fff;
    padding: 30rpx;
    margin-bottom: 20rpx;
    border-radius: 12rpx;

    .evaluation-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 20rpx;

      .user-info {
        display: flex;
        align-items: center;

        .user-avatar {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
          margin-right: 20rpx;
        }

        .user-detail {
          .user-name {
            font-size: 28rpx;
            color: #333;
            font-weight: bold;
            margin-bottom: 8rpx;
            display: block;
          }

          .score-stars {
            display: flex;
            
            .star {
              font-size: 24rpx;
              color: #ddd;
              margin-right: 4rpx;
              
              &.active {
                color: #ffb800;
              }
            }
          }
        }
      }

      .evaluation-time {
        font-size: 24rpx;
        color: #999;
      }
    }

    .evaluation-content {
      font-size: 28rpx;
      color: #333;
      line-height: 1.6;
      margin-bottom: 20rpx;
    }

    .evaluation-actions {
      display: flex;
      padding-top: 20rpx;
      border-top: 1rpx solid #f5f5f5;

      .action-item {
        display: flex;
        align-items: center;
        margin-right: 40rpx;

        .icon {
          font-size: 32rpx;
          margin-right: 10rpx;

          &.active {
            color: #ff4d4f;
          }
        }

        .count {
          font-size: 24rpx;
          color: #999;
        }
      }
    }

    .reply-list {
      margin-top: 20rpx;
      background: #f9f9f9;
      border-radius: 8rpx;
      padding: 20rpx;

      .reply-item {
        padding: 10rpx 0;
        font-size: 26rpx;
        border-bottom: 1rpx solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .reply-user {
          color: #1890ff;
          font-weight: 500;
          margin-right: 10rpx;
        }

        .reply-content {
          color: #333;
        }

        .reply-time {
          font-size: 24rpx;
          color: #999;
          margin-top: 10rpx;
          display: block;
        }
      }
    }

    .reply-input-container {
      display: flex;
      margin-top: 20rpx;
      align-items: center;
      
      .reply-input {
        flex: 1;
        height: 70rpx;
        background: #f5f5f5;
        border-radius: 35rpx;
        padding: 0 20rpx;
        font-size: 26rpx;
      }
      
      .reply-submit {
        width: 120rpx;
        height: 70rpx;
        line-height: 70rpx;
        background: #1890ff;
        color: #fff;
        font-size: 26rpx;
        border-radius: 35rpx;
        margin-left: 20rpx;
        text-align: center;
        padding: 0;
      }
    }
  }
}

.emergency-buy-btn {
  position: fixed;
  bottom: 120rpx;
  right: 30rpx;
  width: 100rpx;
  height: 100rpx;
  background: #ff5500;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  box-shadow: 0 6rpx 20rpx rgba(255, 85, 0, 0.3);
  z-index: 999;
}

/* 底部操作栏 - 提高层级并增强可点击性 */
.action-bar {
  z-index: 900 !important; /* 提高层级 */
}

/* 购物车图标 - 增大点击区域 */
.action-icons .icon-item {
  padding: 10rpx; /* 增加内边距扩大点击区域 */
  margin-right: 20rpx;
}

/* 购买按钮 - 提高层级和增强点击行为 */
.buy-buttons button {
  z-index: 950 !important;
  position: relative;
  transform: translateZ(0); /* 启用GPU加速 */
  transition: all 0.2s;
  
  &:active {
    transform: scale(0.98);
    opacity: 0.9;
  }
}

/* 数量选择器 - 改进点击响应 */
.quantity-selector .selector {
  .minus, .plus {
    z-index: 10;
    position: relative;
    padding: 0;
    width: 80rpx; /* 增大宽度 */
    height: 80rpx; /* 增大高度 */
    
    &:active {
      background-color: #e0e0e0;
    }
  }
  
  .quantity-input {
    z-index: 5;
    padding: 0 10rpx;
  }
}

/* 弹窗样式优化 - 确保正确的层叠顺序 */
.quantity-popup {
  z-index: 9999 !important;
  
  .popup-footer .confirm-btn {
    z-index: 10000 !important;
    position: relative;
  }
}

/* 优化评价表单样式 */
.evaluation-form {
    background: #fff;
    border-radius: 24rpx 24rpx 0 0;
    padding-bottom: env(safe-area-inset-bottom);
    max-height: 90vh;
    overflow-y: auto;
    
    .form-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24rpx 30rpx;
      border-bottom: 1px solid #f0f0f0;
      
      .title {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
      }
      
      .close {
        font-size: 36rpx;
        color: #999;
        padding: 10rpx;
      }
    }
    
    .form-content {
      padding: 30rpx;
      
      .rating-box {
        margin-bottom: 30rpx;
        
        .rating-item {
          display: flex;
          align-items: center;
          margin-bottom: 20rpx;
          
          .rating-label {
            width: 160rpx;
            font-size: 28rpx;
            color: #333;
          }
          
          .stars {
            display: flex;
            
            .star {
              font-size: 40rpx;
              color: #ddd;
              margin-right: 10rpx;
              
              &.active {
                color: #ffb800;
              }
            }
          }
        }
      }
      
      .content-box {
        margin-bottom: 30rpx;
        
        .label {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 20rpx;
          display: block;
        }
        
        .evaluation-textarea {
          width: 100%;
          height: 200rpx;
          background: #f8f8f8;
          border-radius: 12rpx;
          padding: 20rpx;
          font-size: 26rpx;
          box-sizing: border-box;
        }
        
        .word-count {
          font-size: 24rpx;
          color: #999;
          text-align: right;
          margin-top: 10rpx;
          display: block;
        }
      }
      
      .anon-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30rpx;
        
        .label {
          font-size: 28rpx;
          color: #333;
        }
      }
    }
    
    .form-footer {
      padding: 20rpx 30rpx 40rpx;
      
      .submit-btn {
        height: 88rpx;
        line-height: 88rpx;
        background: #1890ff;
        color: #fff;
        font-size: 30rpx;
        border-radius: 44rpx;
        text-align: center;
        box-shadow: 0 8rpx 16rpx rgba(24, 144, 255, 0.2);
        border: none;
        
        &:disabled {
          opacity: 0.6;
        }
        
        &:active {
          opacity: 0.8;
          transform: scale(0.98);
        }
      }
    }
  }

  .quantity-selector {
    margin: 20rpx 0;
    
    .label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 10rpx;
      display: block;
    }
    
    .selector {
      display: flex;
      align-items: center;
      height: 60rpx;
      
      .minus, .plus {
        width: 60rpx;
        height: 60rpx;
        line-height: 60rpx;
        text-align: center;
        background: #f5f5f5;
        font-size: 28rpx;
        color: #333;
        
        &.disabled {
          color: #999;
          background: #f0f0f0;
        }
        
        &:active {
          opacity: 0.8;
        }
      }
      
      .quantity-input {
        width: 80rpx;
        height: 60rpx;
        line-height: 60rpx;
        text-align: center;
        font-size: 28rpx;
        color: #333;
        background: #fff;
        margin: 0 10rpx;
        border: 1px solid #eee;
      }
    }
  }

  /* 数量选择器样式优化 */
  .quantity-selector {
    margin: 20rpx 0;
    
    .label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 16rpx;
      display: block;
      font-weight: 500;
    }
    
    .selector {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      height: 70rpx;
      
      .minus, .plus {
        width: 70rpx;
        height: 70rpx;
        line-height: 70rpx;
        text-align: center;
        background: #f5f5f5;
        font-size: 34rpx;
        color: #333;
        font-weight: 500;
        position: relative;
        z-index: 20;
        
        &.disabled {
          color: #999;
          background: #f0f0f0;
        }
        
        &:active {
          background-color: #e0e0e0;
          opacity: 0.9;
        }
      }
      
      .quantity-input {
        width: 100rpx;
        height: 70rpx;
        line-height: 70rpx;
        text-align: center;
        font-size: 30rpx;
        color: #333;
        background: #fff;
        margin: 0 10rpx;
        border: 1px solid #eee;
        position: relative;
        z-index: 10;
      }
    }
  }
</style> 